<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Memory Allocation</title>
  <meta
 content="C++ Tutorial: Memory Allocation"
 name="description" />
  <meta
 content="C++ Tutorial, Memory Allocation, New Operator, Operator New, Delete, New, Delete [], malloc()"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial -   Memory Allocation</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>


<br />
<br />
<img src="images/memoryallocation/SunChunMan.png" alt="SunChunMan"/>
<br />
<br />

<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="automaticmemory">Automatic Memory Management</div>
<p>Before we go into manual memory management, it might be better look at <strong>automatic</strong> memory management.</p>
<p>Automatic memory management is closely related to local variables. A local variable occupies memory that the system allocates when it sees the variable's definition during execution. The system also deallocates that memory automatically at the end of the block that contains the definition.</p>
<p>Programmers sometimes make a mistake of returning invalid pointer as we see in the example below. A pointer becomes invalid once the corresponding variable has been deallocated. </p>
<pre>
int * badPointer() {
	int i;
	return &i;
}
</pre>
<p>
The function badPointer() returns the address of the local variable i. However, when the function returns, actually ends the execution of the block and deallocates i. So, the pointer that &i is now no longer valid. Still, the function tries to return it anyway. What's going to happen? Only the compiler knows.</p>
<p>If we insist on returning the &i, we can use <strong>static</strong>:</p>
<pre>
int * pointerToStatic() {
	<font color="blue">static i;</font>
	return &i;
}
</pre>
<p>This says that i is static and thus we allocate it once and we do not want to deallocate it as long as the code is running.</p>
<br />
<br />

<div class="subtitle" id="automaticmemory">Automatic Memory Management</div>
<p>When we talk about memory management, it's about deallocation since proper deallocation is crucial to the memory management.</p> 
<p>To <strong>allocate</strong> a new object from the free store, C uses the <strong>malloc</strong> function and  C++ uses the <strong>new</strong> operator. While determination of when an object ought to be created is trivial and is not problematic. The critical issue is the determination of when an object is no longer needed and arranging for its underlying storage to be returned to the free store (heap) so that it may be re-used to satisfy future memory requests. In manual memory allocation, this is also specified manually by the programmer; via functions such as <strong>free()</strong> in C, or the <strong>delete</strong> operator in C++.</p>
<br />
<br />

<div class="subtitle" id="newoperator">New Operator and Operator New</div>
<p>What's difference between the <strong>new</strong> operator and <strong>operator new</strong>?</p>
<p>Let's look at the following line of code,:
<pre>
	string *ptrStr = new string("Where is my place in Memory?");
</pre>
<p>the <strong>new</strong> is the <strong>new</strong> operator. Since this operator is built into C++, we can't change the behavior of the operator. What it does is twofold.</p>
<ol>
	<li>It allocates enough memory to hold an object of the type requested. In the above example, it allocates enough memory to hold a <strong>string</strong> object.</li>
	<li>It calls a <strong>constructor</strong> to <strong>initialize</strong> an object in the memory that was allocated.</li>
</ol> 
<p>The <strong>new</strong> operator always does those two things and we can't change its meaning at all.</p>
<p>What we can change is <strong>how</strong> the memory for an object is allocated. The <strong>new</strong> operator calls a function to perform the required memory allocation, and we can <strong>rewrite</strong> or <strong>overload</strong> the function to change what it's doing.</p>
<p>So, what function is the <strong>new</strong> calling?<br />
It is <strong>operator new</strong>.</p>
<pre>
	void * operator new (size_t size);
</pre>
<p>The return type is <strong>void*</strong>. Since this function returns a pointer to <strong>raw</strong> which is <strong>uninitialized</strong> memory. The <strong>size_t</strong> specifies how much memory to allocate.</p>
<p>It's rare but there is a chance we may want to call <strong>operator new</strong> directly.</p>
<pre>
	void *ptrRawMemory = operator new(sizeof(string));
</pre>
<p>The <strong>operator new</strong> returns a pointer to a chunk of memory enough to hole a <strong>string</strong> object. <br />
The <strong>operator new</strong> is similar to <strong>malloc</strong> in that it's responsible only for allocating memory. It knows nothing about constructors. All <strong>operator new</strong> understands is memory allocation. That's it. </p>
<p>It is the job of the <strong>new</strong> operator to take the <strong>raw</strong> memory that the <strong>operator new</strong> returns and make it into an object.</p>
<p>Let's look at the process of memory allocation and initialization from the perspective of compiler. When a compiler sees the following line,</p>
<pre>
	string *ptrStr = new string("Where is my place in Memory?");
</pre>
<p>the compiler generate a code something like this:</p>
<pre>
	void *ptrRawMemory = operator new(sizeof(string));
</pre>
<p>It obtains raw memory for a string object.</p>
<pre>
	call string::string("Where is my place in Memory?") 
	on *ptrRawMemory;
</pre>
<p>It then initialize the object in the memory by calling a constructor.</p>
<pre>
	string *ptrString = static_cast<string*>(memory);
</pre>
<p>The line of code above makes ptrString point to the new object.</p>
<br />
<br />

<div class="subtitle" id="newoperator">New and Delete</div>
<p>When we use a <strong>new</strong> to create an object dynamically, two things happen as we discussed in the previous section: First, memory is allocated by calling <string>operator new</strong>, Second, one or more <strong>constructors</strong> are called for that memory. </p>
<p>Similar things happened when we use <strong>delete</strong>. one or more <strong>destructors</strong> are called for the memory, and then the memory is deallocated using <strong>operator delete</strong>.</p>
<p>The question for <strong>delete</strong> is <strong>how many</strong> objects reside in the memory being deleted? The answer to that question determines how many <strong>destructors</strong> should be called.</p>
<p>So, we should match the <strong>new</strong> and <strong>delete</strong>. Following example demonstrates what it means.</p>
<pre>
	string *ptrString = new string;
	string *ptrStringArray = new string[10];

	<font color="blue">delete</font> ptrString;
	<font color="blue">delete []</font> ptrStringArray;
</pre> 
<p>In the case of array creation, the <strong>new</strong> operator behaves slightly differently from the case of single-object creation. Memory is no longer allocated by <strong>operator new</strong>. Instead, it's allocated by <strong>operator new[]</strong>.</p>
<p>Let's look at the process of creating and deleting array objects.</p>
<p>For arrays, a constructor must be called for <strong>each object</strong> in the array.</p>
<pre>
	string *ptrStringArray = new string[10];	
</pre>
<p>The code calls <strong>operator new[]</strong> to allocate memory for 10 string object, then call the default string constructor for each array element.</p>
<p>In the way, when the delete operator is used on an array, it calls a destructor for each array element and then calls <strong>operator delete[]</strong> to deallocate the memory. It calls the string destructor for each array element, then  calls <strong>operator delete[]</strong> to deallocate the array's memory.</p>
<pre>
	delete [] pstrStringArray;
</pre>
<br />
<br />
<br />

<div class="subtitle" id="freestore">Free Store (C vs. C++)</div>
<p><strong>C</strong> does not provide the <strong>new</strong> and <strong>delete</strong> operators. To use free store, we should use functions dealing with memory. These functions are defined in the <strong>&lt;stdlib.h&gt;</strong>.</p>
<pre>
void* malloc(size_t sz)            /* allocate sz bytes */
void free(void *p)                 /* deallocate the memory pointed to by p */
void* calloc(size_t n, size_t sz); /* allocate n*sz bytes initialized to 0 */
void* realloc(void* p, size_t sz); /* reallocate the memory pointed to by p  
                                      tp a space of size sz */
</pre>
<p>The <strong>typedef sizt_t</strong> is an unsigned type.</p>
<p>Why does <strong>malloc()</strong> return a <strong>void*</strong>?<br />
It's because <strong>malloc()</strong> has no idea which type of object we want to put in that memory. Initialization is our responsibility. For example:</p>
<pre>
#include &lt;stdlib.h&gt;

struct Student {
	const char *name;
	int id;
};

int main()
{
	struct Student s = {"Park", 12345};
	/* allocate */
	struct Student* ss = (struct Student*)malloc(sizeof(Student));
	/* initialize */
	ss->name = "Hong";
	ss->id = 67890;
	return 0;
}
</pre>
<p>Note that we can't write in either C or C++.</p>
<pre>
*ss = {"Lee", 43145};
</pre>
<p>But in C++, after we define a constructor, we can write:</p>
<pre>
Student *ss = new Student("Lee", 43145);
</pre>


<br />
<br />
<img src="images/memoryallocation/SunChunMan2.png" alt="SunChunMan2"/>
<br />
<br />


<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
